import { LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED, NOT_MOUNTED } from "../applications/app.helper";
/**
 * 数组拍平
 * @param {*} fns 
 * @returns 
 */
function flattenFnArray(fns) {
    fns = Array.isArray(fns) ? fns: [fns];

    return function (props) {
        return fns.reduce((p,fn)=>p.then(()=>fn(props)),Promise.resolve());
    }
}

export async function toLoadPromise(app) {
    if (app.loadPromise) {
        return app.loadPromise;
    }
    return (app.loadPromise = Promise.resolve().then(async ()=>{
        app.status = LOADING_SOURCE_CODE;
        // 注意父应用和子应用的传参
        let {bootstrap,mount,unmount} = await app.loadApp(app.customProps);
        app.status = NOT_BOOTSTRAPPED; // 还没有调用bootstrap方法
        // 可能是一个数组 所以需要考虑数组拍平的情况
        app.bootstrap = flattenFnArray(bootstrap);
        app.mount = flattenFnArray(mount);
        app.unmount = flattenFnArray(unmount);
        delete app.loadPromise;
        return app;
    }))
}